package org.ithang.application;


import java.util.Random;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.ithang.application.account.bean.Account;
import org.ithang.application.account.service.AccountService;
import org.ithang.application.bcAddr.bean.BcAddr;
import org.ithang.application.bcAddr.service.BcAddrService;
import org.ithang.application.customer.bean.Customer;
import org.ithang.application.customer.service.CustomerService;
import org.ithang.system.keyvalue.bean.Keyvalue;
import org.ithang.system.keyvalue.service.KeyvalueService;
import org.ithang.tools.lang.DateUtils;
import org.ithang.tools.lang.MD5Util;
import org.ithang.tools.lang.RandomName;
import org.ithang.tools.lang.StrUtils;
import org.ithang.tools.model.Action;
import org.ithang.tools.model.ActionResult;
import org.ithang.tools.model.ErrorInfo;
import org.ithang.tools.redis.JedisUtils;
import org.ithang.tools.redis.Keys;
import org.ithang.tools.sender.SmsSender;
import org.ithang.tools.validate.VCode;
import org.ithang.tools.validate.ValidateCodeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 业务首页面
 * @author zyt
 *
 */
@Controller("applicationIndex")
public class IndexAction extends Action<Object>{

	private Random rdom=new Random(System.currentTimeMillis());
	@Autowired
	private CustomerService customerService;
	
	@Autowired
	private AccountService accountService;
	
	@Autowired
	private BcAddrService bcAddrService;
	
	@Autowired
	private KeyvalueService keyvalueService;
	
	@RequestMapping(value={"/","/app"},method=RequestMethod.GET)
	public String index(){
		return "app/index";
	}
	
	@ResponseBody
	@RequestMapping(value="login",method=RequestMethod.GET)
	public ActionResult login(){
		return error(ErrorInfo.InvalidTokenError);
	}
	
	@ResponseBody
	@RequestMapping(value="/login",method=RequestMethod.POST)
	public ActionResult login(@RequestParam String username,@RequestParam String password,
			            @RequestParam(defaultValue="0",required=false) String remeber){
			            //,@RequestParam("tcode")String tcode,@RequestParam("smscode")String smscode){
		
		String mobile=username;
	/*	if(!_verifyTCode(mobile, tcode)){
			return error(ErrorInfo.VCodeNotExistError);
		}
		
		if(!_verifySMSCode(mobile, smscode)){
			return error(ErrorInfo.VCodeNotExistError);
		}*/
		if(11!=mobile.length()){
			return error(ErrorInfo.InvalidMobileError);
		}
		
		//添加用户认证信息
        Subject subject = SecurityUtils.getSubject();
        if(subject.isRemembered()||subject.isAuthenticated()){
        	return page("app/home");
        }
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username,MD5Util.md5(password));
        
        /*if("1".equals(remeber)){
        	usernamePasswordToken.setRememberMe(true);	
        }*/
        
        //进行验证，这里可以捕获异常，然后返回对应信息
        try{
            subject.login(usernamePasswordToken);
            return page("app/home", subject.getSession().getId());
        }catch(Exception e){
        	e.printStackTrace();
        	return error(ErrorInfo.LoginFailError);
        }
        
	}
	@ResponseBody
	@RequestMapping(value="logout",method={RequestMethod.POST,RequestMethod.GET})
	public ActionResult logout(){
		Subject subject = SecurityUtils.getSubject();
        if(null!=subject){
        	subject.logout();
        }
        return success();
	}
	
	/**
	 * 产出 图形验证码
	 * 传一个唯一性的字符串，如mobile或email
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="freshtcode",method=RequestMethod.GET)
	public ActionResult freshTCode(@RequestParam("mobile")String mobile){
		VCode v = ValidateCodeUtil.getRandomCode();     //直接调用静态方法，返回验证码对象
		if(null!=v){
			if(11!=mobile.length()){
				return error(ErrorInfo.InvalidMobileError);
			}
			String key=Keys.format(Keys.LoginTCode, mobile);
			//JedisUtils.set(key, MD5Util.getEncryptedData(v.getValue().toLowerCase()),60);//将验证码值保存redis中
			Keyvalue kv=keyvalueService.get(Keys.TestDev);
			if(null!=kv&&1==kv.intValue()){
				JedisUtils.set(key, "123456",60*5);//将验证码值保存redis中
			}else{
			    JedisUtils.set(key, v.getValue(),60*5);//将验证码值保存redis中
			}
			return success("data:img/png;base64,"+v.getBase64Str());
		}
        return error(ErrorInfo.UnknowError);
	}
	
	/**
	 * 验证 图片验证码
	 * 传一个唯一性的字符串，如mobile或email
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="verifytcode",method=RequestMethod.GET)
	public ActionResult verifyTCode(@RequestParam("mobile")String mobile,@RequestParam("tcode")String tcode){
		if(_verifyTCode(mobile,tcode)){
			return success();
		}
        return error(ErrorInfo.UnknowError);
	}
	
	/**
	 * 发送短信验证码
	 * @param mobile 手机号
	 * @param vcode 登陆验证码
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="sendsms",method=RequestMethod.GET)
	public ActionResult sendSMS(@RequestParam("mobile")String mobile,@RequestParam("tcode")String tcode){
		String preVCode=JedisUtils.get(Keys.format(Keys.LoginTCode, mobile));
		if(null!=preVCode&&preVCode.trim().length()>0){
			//vcode=MD5Util.getEncryptedData(vcode.toLowerCase());
			if(tcode.equalsIgnoreCase(preVCode)){
				Keyvalue kv=keyvalueService.get(Keys.TestDev);
				if(null!=kv&&1==kv.intValue()){
					JedisUtils.set(Keys.format(Keys.SmsCode,mobile), "123456",60*5);//将验证码值保存redis中
				}else{
					String code=StrUtils.randomNumberCode(6);
					SmsSender.sendMsg(mobile, code);
					JedisUtils.set(Keys.format(Keys.SmsCode,mobile), code,60*5);//将验证码值保存redis中
				}
				return success();
			}
		}else{
			return error(ErrorInfo.VCodeNotExistError);
		}
        return error(ErrorInfo.VCodeNotExistError);
	}
	
	/**
	 * 验证 短信验证码
	 * @param mobile 手机号
	 * @param vcode 登陆验证码
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="verifysmscode",method=RequestMethod.GET)
	public ActionResult verifySMSCode(@RequestParam("mobile")String mobile,@RequestParam("smscode")String smscode){
		if(_verifySMSCode(mobile,smscode)){
			return success();
		}
        return error(ErrorInfo.VCodeNotExistError);
	}
	
	@ResponseBody
	@RequestMapping(value="reg",method=RequestMethod.POST)
	public ActionResult reg(@RequestParam("uname")String uname,@RequestParam("upass")String upass,
			                @RequestParam("mobile")String mobile,@RequestParam("paypass")String paypass,@RequestParam("smscode")String smscode,
			                @RequestParam(value="ycode",required=false)String ycode){
		if(null==mobile||mobile.length()!=11){
			return error(ErrorInfo.InvalidMobileError);
		}
		
		
		Customer user=customerService.getByName(uname);
		if(null!=user){
			return error(ErrorInfo.UserExistError);
		}
		user=customerService.getByMobile(mobile);
		if(null!=user){
			return error(ErrorInfo.MobileExistError);
		}
		
		Customer fromUser=null;
		if(StrUtils.isNotBlank(ycode)){
			fromUser=customerService.getByCode(ycode);
		}
		
		if(_verifySMSCode(mobile, smscode)){
			
			user=new Customer();
			user.setUname(uname);
			user.setUpass(MD5Util.md5(upass));
			user.setMobile(mobile);
			user.setPay_pwd(MD5Util.md5(paypass));
			user.setCreate_time(DateUtils.getSystime());
			user.setTitle(RandomName.randomName(rdom.nextBoolean(), rdom.nextInt(5)));
			if(null!=fromUser){//设置邀请人
				user.setFrom_user(fromUser.getId());
				user.setGrade(fromUser.getGrade()+1);
			}else{
				user.setFrom_user(0);
				user.setGrade(0);
			}
			
			try{
			    customerService.reg(user, fromUser);
			}catch(Exception e){
				e.printStackTrace();
				return error(ErrorInfo.InternalError);
			}
			
		}else{
			return error(ErrorInfo.VCodeNotExistError);
		}
		return success();
	}
	
	/**
	 * 重置密码
	 * @param mobile
	 * @param pwd
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="resetpwd",method=RequestMethod.POST)
	public ActionResult resetPwd(@RequestParam("smscode")String smscode,@RequestParam("mobile")String mobile,@RequestParam("pwd")String pwd){
		
		if(!_verifySMSCode(mobile, smscode)){
			return error(ErrorInfo.VCodeNotExistError);
		}
		
		Customer user=customerService.getByMobile(mobile);
		if(null!=user){
			user.setUpass(MD5Util.md5(pwd));
			customerService.update(user);
		}else{
			return error(ErrorInfo.UserNotExistError);
		}
		return success();
	}
	
	/**
	 * 验证登陆验证码
	 * @param mobile
	 * @return
	 */
	private boolean _verifyTCode(String mobile,String vcode){
		String preVCode=JedisUtils.get(Keys.format(Keys.LoginTCode, mobile));
		if(null!=preVCode&&preVCode.trim().length()>0){
			//vcode=MD5Util.getEncryptedData(vcode.toLowerCase());
			if(vcode.equalsIgnoreCase(preVCode)){
				return true;
			}
		}
		return false;
	}
	
	/**
	 * 验证短信验证码
	 * @param mobile
	 * @param smscode
	 * @return
	 */
	private boolean _verifySMSCode(String mobile,String smscode){
		String preSMSCode=JedisUtils.get(Keys.format(Keys.SmsCode, mobile));
		if(null!=preSMSCode&&preSMSCode.trim().length()>0){
			if(smscode.equalsIgnoreCase(preSMSCode)){
				return true;
			}
		}
		return false;
	}
	
	
	
	
}
